<?php

namespace Modules\H5\Http\Controllers\Bookshelf;

use Modules\Common\Models\Ebooks;
use Modules\Common\Models\Bookshelf;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;

class Bookrack
{
    /**
     * 添加书籍到书架
     * @Route(path=/api/h5/add-to-bookshelf method=post)
     */
    public function addToBookshelf()
    {
        $bookId = request('book_id');
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID;
        $eid = auth('web')->user()->eid;

        // 检查书籍是否已经存在于书架中
        $exists = Bookshelf::where('ebook_id', $bookId)->where('user_id', $userId)->exists();
        if ($exists) {
            return Api::fail('这本书已经在你的书架上了！', 409);
        }

        // 添加书籍到书架
        Bookshelf::create([
            'ebook_id' => $bookId,
            'user_id' => $userId,
            'eid' => $eid,
            'created_at'=>date('Y-m-d H:i:s')
        ]);

        return Api::success('添加成功');
    }

    /**
     * 从书架删除书籍
     * @Route(path=/api/h5/remove-from-bookshelf method=delete)
     */
    public function removeFromBookshelf()
    {

        $bookIdsString = request('book_ids'); // 接收字符串形式的书籍ID
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID
    
        // 将字符串转换为数组
        $bookIds = explode(',', $bookIdsString);
    
        // 确保数组不为空
        if (empty($bookIds)) {
            return Api::fail('无效的书籍ID列表', 400);
        }
    
        // 从书架删除多本书籍
        $deleted = Bookshelf::whereIn('ebook_id', $bookIds)->where('user_id', $userId)->delete();
    
        if ($deleted) {
            return Api::success('书籍已成功从书架上移除！');
        } else {
            return Api::fail('书架上找不到这些书籍！', 404);
        }
    }

    /**
     * 获取用户书架上的所有书籍
     * @Route(path=/api/h5/get-bookshelf)
     */
    public function getBookshelf()
    {
        // 获取当前认证的用户ID
        $userId = auth('web')->user()->id;
        
        // 获取用户的书籍，并按添加到书架的时间降序排序
        $bookshelfRecords = Bookshelf::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->get(['ebook_id', 'created_at']);
        
        // 创建一个以电子书ID为键，添加到书架时间为值的数组
        $addedAtTimes = $bookshelfRecords->mapWithKeys(function ($item) {
            return [$item['ebook_id'] => $item['created_at']->toDateTimeString()];
        })->all();
        
        // 获取所有已发布的电子书ID
        $ebookIds = array_keys($addedAtTimes);
        
        // 构建查询，根据书架记录中的电子书ID过滤电子书
        $ebooksQuery = Ebooks::whereIn('id', $ebookIds)
            ->where('is_published', 1)
            ->with(['category', 'adminUser', 'userReadingRecords']);
        
        // 在查询时就完成排序
        $ebooksQuery->orderByRaw('FIELD(id, ' . implode(',', array_keys($addedAtTimes)) . ')');
        
        // 分页查询
        $ebooks = $ebooksQuery->paginate(request('per_page', 15));
        
        // 返回分页结果，确保data是数组格式
        return Api::success([
            'current_page' => $ebooks->currentPage(),
            'data' => $ebooks->items(),
            'total' => $ebooks->total(),
            'per_page' => $ebooks->perPage(),
            'last_page' => $ebooks->lastPage(),
            'from' => $ebooks->firstItem(),
            'to' => $ebooks->lastItem(),
            "first_page_url" => $ebooks->url(1),
            "last_page_url" => $ebooks->url($ebooks->lastPage()),
            "next_page_url" => $ebooks->nextPageUrl(),
            "path" => $ebooks->path(),
            "prev_page_url" => $ebooks->previousPageUrl(),
        ]);
    
    }
    /**
     * 更新书架中的书籍信息
     * @Route(path=/api/h5/update-bookshelf)
     */
    public function updateBookshelf()
    {

        $bookId = request('book_id');
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID;
        $status = request('status');

        // 更新书架中的书籍信息
        $updated = Bookshelf::where('ebook_id', $bookId)->where('user_id', $userId)->update(['status' => $status]);

        if ($updated) {
            return Api::success('书籍信息更新成功！');
        } else {
            return Api::fail('书架上找不到该书籍', 404);
        }
    }
}